package org.dromara.genealogy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.TreeBuildUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.genealogy.domain.GeName;
import org.dromara.genealogy.domain.vo.GeNameTranVo;
import org.dromara.genealogy.domain.vo.GeNameVo;
import org.springframework.stereotype.Service;
import org.dromara.genealogy.domain.bo.GeNameDraftBo;
import org.dromara.genealogy.domain.vo.GeNameDraftVo;
import org.dromara.genealogy.domain.GeNameDraft;
import org.dromara.genealogy.mapper.GeNameDraftMapper;
import org.dromara.genealogy.service.IGeNameDraftService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 世代名称Service业务层处理
 *
 * @author qianjm
 * @date 2025-10-23
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class GeNameDraftServiceImpl implements IGeNameDraftService {

    private final GeNameDraftMapper baseMapper;

    /**
     * 查询世代名称
     *
     * @param id 主键
     * @return 世代名称
     */
    @Override
    public GeNameDraftVo queryById(Long id){
        GeNameDraftVo vo = baseMapper.selectVoById(id);
        //获取孩子节点
        List<GeNameDraftVo> childrenList = baseMapper.selectVoList(Wrappers.<GeNameDraft>lambdaQuery().eq(GeNameDraft::getParentId, id).isNull(GeNameDraft::getOtherId));
        vo.setSonNum((int)childrenList.stream().filter(x -> "0".equals(x.getGender())).count());
        vo.setDaughterNum((int)childrenList.stream().filter(x -> "1".equals(x.getGender())).count());
        vo.setChildrenList(childrenList);
        //获取妻子数据
        List<GeNameDraftVo> wifeList = baseMapper.selectVoList(Wrappers.<GeNameDraft>lambdaQuery().eq(GeNameDraft::getOtherId, id));
        vo.setWifeList(wifeList);
        return vo;
    }

    /**
     * 分页查询世代名称列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 世代名称分页列表
     */
    @Override
    public Page<GeNameDraftVo>  queryPageList(GeNameDraftBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GeNameDraft> lqw = buildQueryWrapper(bo);
        Page<GeNameDraftVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return result;
    }

    /**
     * 查询符合条件的世代名称列表
     *
     * @param bo 查询条件
     * @return 世代名称列表
     */
    @Override
    public List<GeNameDraftVo> queryList(GeNameDraftBo bo) {
        LambdaQueryWrapper<GeNameDraft> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GeNameDraft> buildQueryWrapper(GeNameDraftBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GeNameDraft> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(GeNameDraft::getGeneName);
        lqw.isNull(GeNameDraft::getOtherId);
        lqw.ge(bo.getGeneName()!=null, GeNameDraft::getGeneName, bo.getGeneName());
        lqw.like(StringUtils.isNotBlank(bo.getName()), GeNameDraft::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getLastName()), GeNameDraft::getLastName, bo.getLastName());
        lqw.like(StringUtils.isNotBlank(bo.getCommonName()), GeNameDraft::getCommonName, bo.getCommonName());
        lqw.eq(StringUtils.isNotBlank(bo.getAlias()), GeNameDraft::getAlias, bo.getAlias());
        lqw.eq(StringUtils.isNotBlank(bo.getMark()), GeNameDraft::getMark, bo.getMark());
        lqw.eq(bo.getParentId() != null, GeNameDraft::getParentId, bo.getParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getRelation()), GeNameDraft::getRelation, bo.getRelation());
        lqw.like(StringUtils.isNotBlank(bo.getParentName()), GeNameDraft::getParentName, bo.getParentName());
        lqw.eq(StringUtils.isNotBlank(bo.getRankNo()), GeNameDraft::getRankNo, bo.getRankNo());
        lqw.eq(StringUtils.isNotBlank(bo.getSchool()), GeNameDraft::getSchool, bo.getSchool());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessional()), GeNameDraft::getProfessional, bo.getProfessional());
        lqw.eq(StringUtils.isNotBlank(bo.getDegree()), GeNameDraft::getDegree, bo.getDegree());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), GeNameDraft::getGender, bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getDuties()), GeNameDraft::getDuties, bo.getDuties());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), GeNameDraft::getTitle, bo.getTitle());
        lqw.eq(bo.getBirthday()!=null, GeNameDraft::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), GeNameDraft::getStatus, bo.getStatus());
        lqw.eq(bo.getDeadTime()!=null, GeNameDraft::getDeadTime, bo.getDeadTime());
        lqw.eq(StringUtils.isNotBlank(bo.getBurialSite()), GeNameDraft::getBurialSite, bo.getBurialSite());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonType()), GeNameDraft::getPersonType, bo.getPersonType());
        lqw.eq(bo.getOtherId() != null, GeNameDraft::getOtherId, bo.getOtherId());
        lqw.eq(bo.getGeId() != null, GeNameDraft::getGeId, bo.getGeId());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), GeNameDraft::getAvatar, bo.getAvatar());
        lqw.eq(StringUtils.isNotBlank(bo.getDegreeStatus()), GeNameDraft::getDegreeStatus, bo.getDegreeStatus());
        lqw.and(StringUtils.isNotBlank(bo.getKeyWord()),q -> q.like(GeNameDraft::getLastName, bo.getKeyWord()).or().like(GeNameDraft::getGeneName, bo.getKeyWord()));
        return lqw;
    }

    /**
     * 新增世代名称
     *
     * @param bo 世代名称
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(GeNameDraftBo bo) {
        GeNameDraft add = MapstructUtils.convert(bo, GeNameDraft.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改世代名称
     *
     * @param bo 世代名称
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(GeNameDraftBo bo) {
        GeNameDraft update = MapstructUtils.convert(bo, GeNameDraft.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GeNameDraft entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除世代名称信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<Tree<Long>> genealogyNameTreeList(GeNameDraftBo bo) {
        LambdaQueryWrapper<GeNameDraft> lqw = buildQueryWrapper(bo);
        List<GeNameDraft> list = baseMapper.selectList(lqw);
        return buildTreeSelect(list);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param nameList 目录列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<Long>> buildTreeSelect(List<GeNameDraft> nameList) {
        if (CollUtil.isEmpty(nameList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.buildMultiRoot(
            nameList,
            GeNameDraft::getId,
            GeNameDraft::getParentId,
            (node, treeNode) ->{
                treeNode.setId(node.getId())
                    .setParentId(node.getParentId())
                    .setName(node.getName()+node.getLastName())
                    .putExtra("disabled", SystemConstants.DISABLE.equals(node.getDelFlag()));
                treeNode.putExtra("geId", node.getGeId());
                treeNode.putExtra("geneName",node.getGeneName());
                treeNode.putExtra("gender",node.getGender());
                treeNode.putExtra("rankNo",node.getRankNo());
                treeNode.putExtra("spouseList", nameList.stream().filter(item -> item.getOtherId() != null && item.getOtherId().equals(node.getId())).collect(Collectors.toList()));
            }
        );
    }

    /**
     * 查询世代名称
     *
     * @param id 主键
     * @return 世代名称
     */
    @Override
    public GeNameTranVo queryTransById(Long id){
        GeNameDraft geNameDraft = baseMapper.selectById(id);
        GeNameTranVo vo = null;
        if(ObjectUtils.isNotNull(geNameDraft)){
            vo = MapstructUtils.convert(geNameDraft, GeNameTranVo.class);
            //获取孩子节点
            List<GeNameDraft> childrenList = baseMapper.selectList(Wrappers.<GeNameDraft>lambdaQuery().eq(GeNameDraft::getParentId, id).isNull(GeNameDraft::getOtherId));
            vo.setSonNum((int)childrenList.stream().filter(x -> "0".equals(x.getGender())).count());
            vo.setDaughterNum((int)childrenList.stream().filter(x -> "1".equals(x.getGender())).count());
            vo.setChildrenList(MapstructUtils.convert(childrenList, GeNameTranVo.class));
            //获取妻子数据
            List<GeNameDraft> wifeList = baseMapper.selectList(Wrappers.<GeNameDraft>lambdaQuery().eq(GeNameDraft::getOtherId, id));
            vo.setWifeList(MapstructUtils.convert(wifeList, GeNameTranVo.class));
        }
        return vo;
    }
}
